package org.example.util.log.text;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import static java.sql.Types.BOOLEAN;
import static java.sql.Types.NUMERIC;
import static org.apache.xmlbeans.impl.piccolo.xml.Piccolo.STRING;

/**
 * @auther admin闫
 * @Descriptopn POI处理Excel表格
 * @date 2024/5/14 19:59
 */
public class ExcelUtil {


    /**
     * 读取Excel文件并返回其内容为二维字符串数组
     *
     * @param filePath Excel文件路径
     * @return 二维字符串数组，每个内部数组代表一行数据
     * @throws IOException 文件读取异常
     */
    public static String[][] readExcel(String filePath) throws IOException {
        FileInputStream fis = null;
        Workbook workbook = null;
        try {
            // 初始化文件输入流和工作簿
            fis = new FileInputStream(new File(filePath));
            workbook = new XSSFWorkbook(fis);

            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);

            // 获取最后一行的行号
            int lastRowNum = sheet.getLastRowNum();

            // 初始化结果数组，假设第一行为标题，不计入数据行
            String[][] data = new String[lastRowNum][];

            // 从第二行开始读取数据
            for (int rowIndex = 1; rowIndex <= lastRowNum; rowIndex++) {
                Row row = sheet.getRow(rowIndex);
                if (row != null) {
                    // 获取该行最后一个单元格的列号
                    int lastCellNum = row.getLastCellNum();
                    data[rowIndex - 1] = new String[lastCellNum]; // 初始化当前行的数组

                    for (int cellIndex = 0; cellIndex < lastCellNum; cellIndex++) {
                        Cell cell = row.getCell(cellIndex, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                        // 根据单元格类型读取数据
                        data[rowIndex - 1][cellIndex] = cell.toString();
                    }
                }
            }

            return data;
        } finally {
            // 关闭资源
            if (workbook != null) {
                workbook.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
    }
}
